package com.triones.api.service.interlace.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.triones.api.entity.BankCardTypeDO;
import com.triones.api.entity.interlace.dto.InterlaceCardBinsDO;
import com.triones.api.entity.interlace.vo.InterlaceCardBinsVO;
import com.triones.api.mapper.interlace.InterlaceCardBinsMapper;
import com.triones.api.service.interlace.InterlaceCardBinsService;
import com.triones.api.service.third.InterlaceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * interlace 卡bins
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InterlaceCardBinsServiceImpl implements InterlaceCardBinsService {

    @Value("${spring.profiles.active}")
    private String activeProfile;

    private final InterlaceService interlaceService;

    private final InterlaceCardBinsMapper interlaceCardBinsMapper;

    @Override
    public boolean checkCardBins(InterlaceCardBinsDO dto) {
        boolean exist = interlaceCardBinsMapper.exists(new LambdaQueryWrapper<InterlaceCardBinsDO>()
            .eq(InterlaceCardBinsDO::getBin, dto.getBin())
            .eq(InterlaceCardBinsDO::getType, dto.getType())
            .eq(InterlaceCardBinsDO::getCurrencies, dto.getCurrencies())
            .eq(InterlaceCardBinsDO::getNetwork, dto.getNetwork())
            .eq(InterlaceCardBinsDO::getEnv, activeProfile)
            .eq(InterlaceCardBinsDO::getDel, "0")
            .ne(ObjectUtil.isNotNull(dto.getId()), InterlaceCardBinsDO::getId, dto.getId()));
        return !exist;
    }

    @Override
    public TableDataInfo<InterlaceCardBinsVO> selectPageList(InterlaceCardBinsDO dto, PageQuery pageQuery) {
        LambdaQueryWrapper<InterlaceCardBinsDO> lqw = new LambdaQueryWrapper<InterlaceCardBinsDO>();
        lqw.eq(StringUtils.isNotEmpty(dto.getStatus()), InterlaceCardBinsDO::getStatus, dto.getStatus())
            .like(StringUtils.isNotEmpty(dto.getBin()), InterlaceCardBinsDO::getBin, dto.getBin())
            .like(StringUtils.isNotEmpty(dto.getType()), InterlaceCardBinsDO::getType, dto.getType())
            .like(StringUtils.isNotEmpty(dto.getNetwork()), InterlaceCardBinsDO::getNetwork, dto.getNetwork())
            .like(StringUtils.isNotEmpty(dto.getCurrencies()), InterlaceCardBinsDO::getCurrencies, dto.getCurrencies())
            .eq(InterlaceCardBinsDO::getDel, "0")
            .eq(InterlaceCardBinsDO::getEnv, activeProfile)
            .orderByAsc(InterlaceCardBinsDO::getCreateTime);
        Page<InterlaceCardBinsVO> page = interlaceCardBinsMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    @Override
    public boolean matchCardBin(String bin) {
        List<Map> response = this.interlaceService.availableCardBINs();
        if (response != null && response.size() > 0) {
            for (Map map : response) {
                List<String> currenciesArr = (List<String>) map.get("currencies");
                String currencies = null;
                if (currenciesArr != null && currenciesArr.size() > 0) {
                    currencies = String.join(",", currenciesArr);
                }
                String binNo = Convert.toStr(map.get("bin"));
                String type = Convert.toStr(map.get("type"));
                String network = Convert.toStr(map.get("network"));
                if (bin.equals(binNo)) {
                    InterlaceCardBinsDO interlaceCardBinsDO = interlaceCardBinsMapper.selectOne(new LambdaQueryWrapper<InterlaceCardBinsDO>()
                        .eq(InterlaceCardBinsDO::getType, type)
                        .eq(InterlaceCardBinsDO::getBin, binNo)
                        .eq(InterlaceCardBinsDO::getCurrencies, currencies)
                        .eq(InterlaceCardBinsDO::getNetwork, network)
                        .eq(InterlaceCardBinsDO::getEnv, activeProfile)
                        .eq(InterlaceCardBinsDO::getDel, "0"));
                    if (interlaceCardBinsDO != null) {
                        interlaceCardBinsDO.setType(type);
                        interlaceCardBinsDO.setCardType(Convert.toStr(map.get("cardType")));
                        interlaceCardBinsDO.setIpr(Convert.toBool(map.get("ipr")) ? 1 : 0);
                        interlaceCardBinsDO.setCurrencies(currencies);
                        interlaceCardBinsDO.setNetwork(network);
                        Map verification = (Map) map.get("verification");
                        if (verification != null) {
                            interlaceCardBinsDO.setAvs(Convert.toBool(verification.get("avs")) ? 1 : 0);
                            interlaceCardBinsDO.setThreeDs(Convert.toBool(verification.get("threeDs")) ? 1 : 0);
                        }
                        Map purchaseLimit = (Map) map.get("purchaseLimit");
                        if (purchaseLimit != null) {
                            interlaceCardBinsDO.setPurchaseLimitDay(Convert.toStr(purchaseLimit.get("day")));
                            interlaceCardBinsDO.setPurchaseLimitSingle(Convert.toStr(purchaseLimit.get("single")));
                            interlaceCardBinsDO.setPurchaseLimitLifetime(Convert.toStr(purchaseLimit.get("lifetime")));
                        }
                        interlaceCardBinsDO.setUpdateTime(System.currentTimeMillis());
                        interlaceCardBinsMapper.updateById(interlaceCardBinsDO);
                    } else {
                        interlaceCardBinsDO = new InterlaceCardBinsDO();
                        interlaceCardBinsDO.setBin(binNo);
                        interlaceCardBinsDO.setType(type);
                        interlaceCardBinsDO.setCardType(Convert.toStr(map.get("cardType")));
                        interlaceCardBinsDO.setIpr(Convert.toBool(map.get("ipr")) ? 1 : 0);
                        interlaceCardBinsDO.setCurrencies(currencies);
                        interlaceCardBinsDO.setNetwork(network);
                        Map verification = (Map) map.get("verification");
                        if (verification != null) {
                            interlaceCardBinsDO.setAvs(Convert.toBool(verification.get("avs")) ? 1 : 0);
                            interlaceCardBinsDO.setThreeDs(Convert.toBool(verification.get("threeDs")) ? 1 : 0);
                        }
                        Map purchaseLimit = (Map) map.get("purchaseLimit");
                        if (purchaseLimit != null) {
                            interlaceCardBinsDO.setPurchaseLimitDay(Convert.toStr(purchaseLimit.get("day")));
                            interlaceCardBinsDO.setPurchaseLimitSingle(Convert.toStr(purchaseLimit.get("single")));
                            interlaceCardBinsDO.setPurchaseLimitLifetime(Convert.toStr(purchaseLimit.get("lifetime")));
                        }
                        interlaceCardBinsDO.setEnv(activeProfile);
                        interlaceCardBinsDO.setCreateTime(System.currentTimeMillis());
                        interlaceCardBinsDO.setUpdateTime(System.currentTimeMillis());
                        interlaceCardBinsMapper.insert(interlaceCardBinsDO);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public InterlaceCardBinsVO getDetail(Long id) {
        return interlaceCardBinsMapper.selectVoById(id);
    }

    @Override
    public boolean edit(InterlaceCardBinsDO dto) {
        InterlaceCardBinsDO cardBinsDO = interlaceCardBinsMapper.selectById(dto.getId());
        if (cardBinsDO == null) {
            throw new SecurityException("卡bin信息不存在！");
        }
        cardBinsDO.setCover(dto.getCover());
        cardBinsDO.setStatus(dto.getStatus());
        cardBinsDO.setIntroduce(dto.getIntroduce());
        cardBinsDO.setUpdateTime(System.currentTimeMillis());
        return interlaceCardBinsMapper.updateById(cardBinsDO) > 0;
    }

    @Override
    public boolean changeShowStatus(InterlaceCardBinsDO dto) {
        InterlaceCardBinsDO cardBinsDO = interlaceCardBinsMapper.selectById(dto.getId());
        if (cardBinsDO == null) {
            throw new ServiceException("未找到该记录");
        }
        cardBinsDO.setStatus(dto.getStatus());
        return interlaceCardBinsMapper.updateById(cardBinsDO) > 0;
    }

    @Override
    public boolean remove(Long id) {
        InterlaceCardBinsDO cardBinsDO = interlaceCardBinsMapper.selectById(id);
        if (cardBinsDO == null) {
            throw new ServiceException("未找到该记录");
        }
        cardBinsDO.setDel("1");
        return interlaceCardBinsMapper.updateById(cardBinsDO) > 0;
    }
}
